package cn.edu.ssm.controller;


import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.edu.ssm.entity.Media;
import cn.edu.ssm.service.MediaService;
import cn.edu.ssm.utils.DateConvert;

@Controller
@RequestMapping("/manage")
public class MediaController {
    @Autowired
    private MediaService mediaService;
    //显示媒体管理界面
    @RequestMapping("/mediamanage.action")
    public String mediaManage(Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum) throws Exception {
    	PageHelper.startPage(pageNum,7);
    	List<Media> list=mediaService.getMediaList();
    	PageInfo<Media> pageInfo = new PageInfo<Media>(list);
    	model.addAttribute("pageInfo",pageInfo); 
    	model.addAttribute("url", "mediamanage");
    	return "manage/media_manage";
    }
    //删除操作
    @RequestMapping("/delete.action")
    @ResponseBody
    public Boolean delete(Model model,@RequestParam String mediaid,HttpServletResponse response) throws IOException {
    	Boolean b=mediaService.delete(mediaid);
    	if(b==true) {
//			 重定向到媒体管理
    		response.sendRedirect("mediamanage.action");
    		return true;		
    	}else {
    		return false;
    	}
		
    }
     
    /**
     * 接收数据页面跳转
     * @return
     * @throws Exception
     */
    @RequestMapping("/editmanager.action")
    public String editmanager(@RequestParam String mediaid,HttpServletRequest request) throws Exception {
    	Media media=mediaService.findById(mediaid);

    	// 页面跳转:
    	request.setAttribute("media", media);    	
    	return "manage/edit_manager";
    }
    

    /**
     * 图片上传并将数据保存到数据库
     * @param uploadFile
     * @param model
     * @param request
     * @param response
     */
    @PostMapping(value = "/updatemanager.action")
    public String fileUpload(MultipartFile uploadFile,Media media, Model model, HttpServletRequest request,HttpServletResponse response)  {
		//文件扩展名
		String extension = FilenameUtils.getExtension(uploadFile.getOriginalFilename());
		String realPath ="";
		String Url = "";
		if(extension.equals("mp4")){
			//realPath表示项目的运行环境目录
			realPath = request.getSession().getServletContext().getRealPath("/medias/videos/");
			System.out.println(realPath+"realPath");
			Url = "/medias/videos/";
		}else{
			realPath = request.getSession().getServletContext().getRealPath("/images/");
			System.out.println(realPath+"realPath");
			Url = "/images/";
		}
    	// 获取到前端传递id
    	String mediaid = request.getParameter("mediaid");
		String isopen = request.getParameter("isopen");
		String screendate = request.getParameter("screendate");
		DateConvert dateConvert  = new DateConvert();
		Date  convert= dateConvert.convert(screendate);
		media.setScreendate(convert);

	
    	//如果图片扩展名不为空就修改图片
    	 if(StringUtils.isNotEmpty(extension)) {
    		//新的文件名字
    	     String newFileName = UUID.randomUUID().toString().replace("-", "");
    		 media.setMediaurl(Url+newFileName+"."+extension);
    		 mediaService.saveFile(media);
			try {
	    		//将图片保存到路径
				uploadFile.transferTo(new File(realPath+"/"+newFileName+"."+extension));
				//跳转到媒体显示页面
	      		return "redirect:/manage/mediamanage.action";
			} catch (Exception e) {
				e.printStackTrace();
			}
    	 }else {
    		  if(mediaid !=null) {
				  String typeid = request.getParameter("typeid");
    			    //修改分类，否则就直接修改其他字段不需要修改图片的url
				  	media.setTypeid(typeid);
				  	media.setIsopen(isopen);
				  	mediaService.uploadMedia(media);
    	    		//跳转到媒体显示页面并
    	     		return "redirect:/manage/mediamanage.action";
    		  }
    	 }
    	 return "manage/edit_manager";
  }
    
    //添加页面跳转
    @RequestMapping("/management.action")
    public String management() throws Exception {
    	   	
    	return "manage/add_manager";
    }
    
    //添加数据
    @PostMapping(value = "/addmanager.action")
    public String addmanager(MultipartFile uploadFile, Model model, HttpServletRequest request,HttpServletResponse response)  {
		//文件扩展名
		String extension = FilenameUtils.getExtension(uploadFile.getOriginalFilename());
		String realPath ="";
		String Url = "";
		if(extension.equals("mp4")){
			realPath = request.getSession().getServletContext().getRealPath("/medias/videos/");
			Url= "/medias/videos/";
		}else{
			realPath = request.getSession().getServletContext().getRealPath("/images/");
			Url= "/images/";
		}
    	Media media = new Media();
    	media.setMediatype(request.getParameter("mediatype"));
    	media.setMediatitle(request.getParameter("mediatitle"));
    	media.setDescription(request.getParameter("description"));
    	media.setTypename(request.getParameter("typename"));
		String screendate = request.getParameter("screendate");
		DateConvert dateConvert  = new DateConvert();
		Date  convert= dateConvert.convert(screendate);
		media.setScreendate(convert);
		String[] parameterValues = request.getParameterValues("typeid");
    	  for (String typeid : parameterValues) {
    		  media.setTypeid(typeid);
		}
    	media.setIsopen(request.getParameter("isopen"));
          //新的文件名字
	     String newFileName = UUID.randomUUID().toString().replace("-", "");
      	media.setMediaurl(Url+newFileName+"."+extension);
      	     	    
		try {
			 //将图片保存到路径
			uploadFile.transferTo(new File(realPath+"/"+newFileName+"."+extension));
			@SuppressWarnings("unused")
			int rows =mediaService.addmanager(media);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
    	return "redirect:/manage/mediamanage.action";
    }
    
  
}
